import { fabric } from 'fabric';

import ObjectPool from './ObjectPool';

class Star extends fabric.Polygon {
  constructor(options = {}) {
    // 创建五角星的点
    const outerRadius = 50;
    const innerRadius = 25;
    const points = [];
    
    for (let i = 0; i < 10; i++) {
      const radius = i % 2 === 0 ? outerRadius : innerRadius;
      const angle = (Math.PI / 5) * i;
      const x = radius * Math.sin(angle);
      const y = -radius * Math.cos(angle);
      points.push({ x, y });
    }

    super(points, {
      fill: '#f39c12',
      strokeWidth: 1,
      stroke: '#000000',
      selectable: true,
      cornerSize: 10,
      transparentCorners: false,
      hasRotatingPoint: true,
      padding: 5,
       id: '',  // 添加id属性
      ...options,
    });

    // 确保控制点颜色与边框颜色一致
    this.set({
      cornerColor: this.stroke,
      borderColor: this.stroke,
    });
  }

  // 更新属性
  updateProps(props) {
    this.set(props);
    if (props.stroke) {
      this.set({
        cornerColor: props.stroke,
        borderColor: props.stroke,
      });
    }
    this.canvas?.requestRenderAll();
    return this;
  }

  // 移到顶层
  bringToFront() {
    if (this.canvas) {
      this.canvas.bringToFront(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 移到底层
  sendToBack() {
    if (this.canvas) {
      this.canvas.sendToBack(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 删除自身
  remove() {
    if (this.canvas) {
      this.canvas.remove(this);
      this.canvas.requestRenderAll();
    }
  }

  // 设置大小
  setSize(size) {
    const scale = size / 100;
    this.scale(scale);
    this.canvas?.requestRenderAll();
    return this;
  }
}

// 创建一个全局的星形对象池
const starPool = new ObjectPool(() => new Star());

// 导出Star类和starPool
export { Star, starPool };
export default Star;
